<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class TopographicMapsController extends AppController {

    var $name = "TopographicMaps";

    public function index($property_id) {
        $this->TopographicMap->recursive = 0;
        $this->set('property_id', $property_id);
        $cod = $this->TopographicMap->Property->field('codigo', array('Property.id' => $property_id));
        $this->Session->write('predio_codigo', $cod);
        $this->Session->write('predio_id', $property_id);
        $this->set('cod', $this->TopographicMap->Property->field('codigo', array('Property.id' => $property_id)));
        $this->set('properties', $this->TopographicMap->find('all', array('conditions' => array('TopographicMap.property_id' => $property_id), 'order' => array('TopographicMap.id DESC'), 'fields' => array('Departament.name', 'City.name', 'TopographicMap.id', 'TopographicMap.observacion', 'TopographicMap.calificacion', 'TopographicMap.vereda', 'TopographicMap.area', 'TopographicMap.cerrado'))));
    }

    public function select() {
        Configure::write('debug', 0);
        $this->set('est', $this->Session->read('estado'));
        $this->set('cities', $this->TopographicMap->City->find('list', array(
                    'order' => 'name ASC',
                    'conditions' => array('City.departament_id' => $this->data['TopographicMap']['departament_id'])
                        )
                ));
    }

    public function add($property_id) {
        $this->layout = "ajax";
        $this->data = $this->TopographicMap->find('first', array('recursive' => -1, 'conditions' => array('TopographicMap.property_id' => $property_id)));

        if (!empty($this->data)) {
            $anterior_id = $this->data['TopographicMap']['id'];
            unset($this->data['TopographicMap']['id']);
            if ($this->TopographicMap->saveAll($this->data)) {
                $last_id = $this->TopographicMap->getLastInsertID();
                $areas = $this->TopographicMap->TopographicArea->find('all', array('recursive' => -1, 'conditions' => array('topographic_map_id' => $anterior_id), 'fields' => array('TopographicArea.magnitud', 'TopographicArea.tipo', 'TopographicArea.area_type_id')));

                foreach ($areas as $area) {
                    unset($area['TopographicArea']['id']);
                    $area['TopographicArea']['topographic_map_id'] = $last_id;
                    $this->TopographicMap->TopographicArea->create();
                    $this->TopographicMap->TopographicArea->saveAll($area);
                }
                $this->Session->setFlash('Registro guardado correctamente');
                $this->redirect(array('Controller' => 'TopographicMaps', 'action' => 'index', $property_id));
            }
        } else {
            $this->TopographicMap->create();
            $this->data = array();
            $this->data['TopographicMap']['property_id'] = $property_id;
            $this->data['TopographicMap']['city_id'] = 0;
            $this->data['TopographicMap']['area'] = 0;

            if ($this->TopographicMap->saveAll($this->data)) {
                $this->Session->setFlash('Registro guardado correctamente');
                $this->redirect(array('Controller' => 'TopographicMaps', 'action' => 'index', $property_id));
            } else {
                var_dump($this->invalidFields());
                debug($this->validationErrors);
                die();
                $this->Session->setFlash('NO GUARDADO');
            }
        }
    }

    public function edit($id) {
        $this->layout = "ajax";
        $this->set('departaments', $this->TopographicMap->Departament->find('list', array('order' => array('Departament.name ASC'))));
        $this->set('cities', $this->TopographicMap->City->find('list', array('City.name ASC')));
        if (!empty($this->data)) {
            if (!is_numeric($this->data['TopographicMap']['area'])){
                $this->data['TopographicMap']['area'] = 0;
            }
            if ($this->TopographicMap->saveAll($this->data)) {
                if ($this->data['TopographicMap']['archivo']['tmp_name'] != "") {
                    $codigo_predio = $this->TopographicMap->Property->field('Property.codigo', array('Property.id' => $this->data['TopographicMap']['property_id']));
                    $nombreArchivo = $codigo_predio . "-" . $id . ".pdf";
                    $rutaArchivo = APP . "webroot" . "/" . "files" . "/planos";

                    if (!is_dir($rutaArchivo)) {
                        if (!mkdir($rutaArchivo)) {
                            echo "error creando archivo";
                            //redirect
                        }
                    }
                    $rutaArchivo.= "/" . $nombreArchivo;
                    if (move_uploaded_file($this->data['TopographicMap']['archivo']['tmp_name'], $rutaArchivo)) {
                        $this->Session->setFlash('Archivo cargado con éxito', 'flash_custom');
                        $this->redirect(array('controller' => 'Pages', 'action' => 'display'));
                    } else {
                        $this->Session->setFlash('No es posible cargar el archivo', 'flash_custom');
                        $this->redirect(array('controller' => 'Pages', 'action' => 'display'));
                    }
                }
                $this->Session->setFlash('Registro guardado correctamente' . $this->data['TopographicMap']['archivo']['tmp_name']);
                $this->redirect(array('controller' => 'Pages', 'action' => 'display'));
            } else {
                $this->Session->setFlash('No fue posible guardar los datos, por favor verifique que los campos esten correctamente diligenciados22222.');
                $this->TopographicMap->recursive = -1;
                $this->data = $this->TopographicMap->find('first', array('conditions' => array('TopographicMap.id' => $id)));
                $this->TopographicMap->Property->recursive = -1;
                $revision = $this->TopographicMap->Property->find('first', array('conditions' => array('Property.id' => $this->data['TopographicMap']['property_id']), 'fields' => array('City.name', 'City.id', 'City.departament_id', 'Property.*', 'Departament.name'), 'joins' => array(array('table' => 'cities', 'alias' => 'City', 'type' => 'LEFT', 'conditions' => array('Property.city_id=City.id')), array('table' => 'departaments', 'alias' => 'Departament', 'type' => 'left', 'conditions' => array('City.departament_id=Departament.id')))));
                $this->set('revision', $revision);
            }
        } else {
            $this->TopographicMap->recursive = -1;
            $this->data = $this->TopographicMap->find('first', array('conditions' => array('TopographicMap.id' => $id)));
            $this->TopographicMap->Property->recursive = -1;
            $revision = $this->TopographicMap->Property->find('first', array('conditions' => array('Property.id' => $this->data['TopographicMap']['property_id']), 'fields' => array('City.name', 'City.id', 'City.departament_id', 'Property.*', 'Departament.name'), 'joins' => array(array('table' => 'cities', 'alias' => 'City', 'type' => 'LEFT', 'conditions' => array('Property.city_id=City.id')), array('table' => 'departaments', 'alias' => 'Departament', 'type' => 'left', 'conditions' => array('City.departament_id=Departament.id')))));
            $this->set('revision', $revision);
        }
    }

//    function delete($id, $property_id) {
//        if ($this->TopographicMap->delete($id)) {
//            $this->Session->setFlash('Registro borrado correctamente');
//            $this->redirect(array('Controller' => 'TopographicMap', 'action' => 'index', $property_id));
//        }
//    }

    public function reportAreas() {
        $this->layout = "csv";
        ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
        //create a file
        $filename = "Reporte_areas_plano_topografico_" . date("Y.m.d") . ".csv";
        $csv_file = fopen('php://output', 'w');
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');


        $sql = "SELECT City.name, Departament.name, Property.matricula, Property.codigo, Proyect.codigo, TopographicMap.area, Property.area_titulo, Property.area_negociacion FROM `topographic_maps` TopographicMap
                JOIN properties Property ON Property.id = TopographicMap.property_id
                JOIN proyects Proyect ON Proyect.id = Property.proyect_id
                JOIN cities City ON City.id = Property.city_id
                JOIN departaments Departament ON Departament.id = City.departament_id
                WHERE TopographicMap.id = ( 
                SELECT MAX( y.id ) AS id
                FROM topographic_maps y
                LEFT JOIN properties x ON x.id = y.property_id
                WHERE x.codigo = Property.codigo ) 
                GROUP BY Property.codigo
                ORDER BY TopographicMap.id ASC ";
        $results = $this->TopographicMap->query($sql);


        // The column headings of your .csv file   
        $header_row = array("CÓDIGO PROYECTO", "CÓDIGO PREDIO", "DEPARTAMENTO", "MUNICIPIO", "FOLIO MATRÍCULA", "ÁREA PLANO TOPOGRÁFICO", "ÁREA TITULO", "ÁREA NEGOCIACIÓN");

        $newRow = array();

        foreach ($header_row as $a) {
            $newRow[] = iconv('UTF-8', 'Windows-1252', $a);
        }

        fputcsv($csv_file, $newRow, ';', '"');

        foreach ($results as $result) {

            $row = array(
                $result['Proyect']['codigo'],
                $result['Property']['codigo'],
                $result['Departament']['name'],
                $result['City']['name'],
                $result['Property']['matricula'],
                number_format($result['TopographicMap']['area'], 4, ",", "."),
                number_format($result['Property']['area_titulo'], 4, ",", "."),
                number_format($result['Property']['area_negociacion'], 4, ",", ".")
            );

            $newRow = array();

            foreach ($row as $a) {
                $newRow[] = iconv('UTF-8', 'Windows-1252', $a);
            }

            fputcsv($csv_file, $newRow, ';', '"');
        }
        fclose($csv_file);
    }

    public function report() {
        $this->layout = "csv";

        ini_set('max_execution_time', 600);
        $filename = "Reporte_planos_topograficos" . date("Y-m-d") . ".csv";
        $csv_file = fopen('php://output', 'w');
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        // Las cabeceras del archivo csv  
        $header_row = array("CÓDIGO PROYECTO", "CÓDIGO DEL PREDIO", "NOMBRE DEL PREDIO", "ÁREA EN EL MAPA", "SUMA DE ÁREAS PARCIALES", "CALIFICACIÓN", "CONCEPTO");
        $newRow = array();

        foreach ($header_row as $a) {
            $newRow[] = iconv('UTF-8', 'Windows-1252', $a);
        }
        fputcsv($csv_file, $newRow, ';', '"');

        //Selecciono todos los proyectos distintos que tengan un plano topográfico
        $sql = "SELECT DISTINCT Proyect.codigo, Property.codigo, Property.id
                FROM topographic_maps TopographicMap
                LEFT JOIN properties Property ON Property.id = TopographicMap.property_id
                LEFT JOIN proyects Proyect ON Proyect.id = Property.proyect_id
                WHERE 1";
        $proyectos = $this->TopographicMap->query($sql);

        foreach ($proyectos as $proyecto) {
            //Selecciono el ultimo plano topográfico hecho para el proyecto
            $sql = "SELECT Property.nombre, Property.codigo, TopographicMap.area, TopographicMap.calificacion, TopographicMap.id, TopographicMap.observacion
                    FROM topographic_maps TopographicMap
                    LEFT JOIN properties Property ON Property.id = TopographicMap.property_id
                    LEFT JOIN proyects Proyect ON Proyect.id = Property.proyect_id
                    WHERE Property.id = " . $proyecto['Property']['id'] . "
                    ORDER BY TopographicMap.id DESC
                    LIMIT 1";
            $plano = $this->TopographicMap->query($sql);

            $calificacion = "";

            $sql = "SELECT SUM( TopographicArea.magnitud ) area 
                    FROM topographic_areas TopographicArea
                    WHERE TopographicArea.topographic_map_id =" . $plano[0]['TopographicMap']['id'] . "
                    GROUP BY TopographicArea.topographic_map_id";
            $area = $this->TopographicMap->query($sql);

            if (!empty($area)) {
                $suma_areas_parciales = $area[0][0]["area"];
            } else {
                $suma_areas_parciales = 0;
            }

            //0=> 'Sin registro',1 => 'Cumple', 2 => 'Subsanable', 3 => 'No cumple'

            switch ($plano[0]['TopographicMap']['calificacion']) {
                case 0:
                    $calificacion = "SIN REGISTRO";
                    break;
                case 1:
                    $calificacion = "CUMPLE";
                    break;
                case 2:
                    $calificacion = "SUBSANABLE";
                    break;
                case 3:
                    $calificacion = "NO CUMPLE";
                    break;

                default:
                    break;
            }

            $fila = array(
                $proyecto['Proyect']['codigo'],
                $plano[0]['Property']['codigo'],
                $plano[0]['Property']['nombre'],
                number_format($plano[0]['TopographicMap']['area'], 2, ',', '.'),
                number_format($suma_areas_parciales, 2, ',', '.'),
                $calificacion,
                $plano[0]['TopographicMap']['observacion']
            );

            $newRow = array();

            foreach ($fila as $a) {
                $newRow[] = iconv('UTF-8', 'Windows-1252', $a);
            }

            fputcsv($csv_file, $newRow, ';', '"');
        }

        fclose($csv_file);
    }

    public function open($map_id, $property_id) {
        $this->layout = "ajax";
        if ($this->TopographicMap->saveField('cerrado', 0, array('TopographicMap.id' => $map_id))) {
            $this->Session->setFlash('Registro abierto para edición', 'flash_custom');
            $this->redirect(array('Controller' => 'TopographicMap', 'action' => 'index', $property_id));
        } else {
            $this->Session->setFlash('No se pudo abrir el registro', 'flash_custom');
            $this->redirect(array('Controller' => 'TopographicMap', 'action' => 'index', $property_id));
        }
    }

    public function close($map_id, $property_id) {
        $this->layout = "ajax";
        //$this->TopographicMap->id=$map_id;
        if ($this->TopographicMap->saveField("cerrado", 1, array('TopographicMap.id' => $map_id))) {
            $this->Session->setFlash('Registro cerrado para edición', 'flash_custom');
            $this->redirect(array('Controller' => 'TopographicMap', 'action' => 'index', $property_id));
        } else {
            $this->Session->setFlash('No se pudo cerrar el registro', 'flash_custom');
            // $this->redirect(array('Controller' => 'TopographicMap', 'action' => 'index', $property_id));
        }
    }

}

?>
